package com.boot.unity.api.wx.utils;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class AdmissionCardUtil {

    private static volatile AdmissionCardUtil instance = null;

    private AdmissionCardUtil() {}

    /**
     * 获取工具类实例
     * @return
     */
    public static AdmissionCardUtil getInstance() {
        if (instance == null){
            synchronized (AdmissionCardUtil.class){
                if (instance == null) {
                    instance = new AdmissionCardUtil();
                }
            }
        }
        return instance;
    }

    /**
     * pdf生成jpg
     * @param map
     * @throws IOException
     */
    public void createJpg(Map<String, String> map) throws IOException {
        String filePath = createPdf(map);
        PDDocument doc = null;
        ByteArrayOutputStream os = null;
        InputStream stream = null;
        OutputStream out = null;
        if (filePath != null) {
            try {
                // pdf路径
                stream = new FileInputStream(filePath);
                // 加载解析PDF文件
                doc = PDDocument.load(stream);
                PDFRenderer pdfRenderer = new PDFRenderer(doc);
                PDPageTree pages = doc.getPages();
                int pageCount = pages.getCount();
                for (int i = 0; i < pageCount; i++) {
                    BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
                    os = new ByteArrayOutputStream();
                    ImageIO.write(bim, "jpg", os);
                    byte[] dataList = os.toByteArray();
                    // jpg文件转出路径
                    String id = map.get("id");
                    String jpgPath = map.get("jpgPath");
                    // String jpgPath = SystemConfig.LITEMALL_SERVICE_PATH + id + "hb.jpg";
                    File file = new File(jpgPath);
                    if (!file.getParentFile().exists()) {
                        // 不存在则创建父目录及子文件
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    }
                    out = new FileOutputStream(file);
                    out.write(dataList);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (doc != null) {
                    doc.close();
                }
                if (os != null) {
                    os.close();
                }
                if (stream != null) {
                    stream.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        }
    }

    /**
     * 根据pdf模板填充
     * @param map
     * @return ysxm
     */
    private String createPdf(Map<String, String> map){
        try {
//            String pdfPath = this.getClass().getClassLoader().getResource("admission/admission.pdf").getPath();
//            String pdfPath = "D:/pdf/admission/admission.pdf";
//            System.out.println("pdfPath::::::"+pdfPath);
            String pdfPath = map.get("pdfPath");
            PdfReader reader = new PdfReader(pdfPath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PdfStamper ps = new PdfStamper(reader, bos);
            // 中文字体问题
            String filePath = map.get("filePath");
            String jpgPath = filePath+"fonts//simhei.ttf";
            BaseFont bf = BaseFont.createFont(jpgPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            fillData(fields, map);
            String imgPath = map.get("imgPath");
            addImage(ps, fields, "logo", imgPath);
            ps.setFormFlattening(true);
            ps.close();
            //生成pdf路径存放的路径
            String id = map.get("id");
            String path = map.get("jpgPath");// + id + "pdf.pdf";
            OutputStream fos = new FileOutputStream(path);
            fos.write(bos.toByteArray());
            fos.flush();
            fos.close();
            bos.close();
            return path;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 填充模板中数据
     * @param fields
     * @param data
     */
    private static void fillData(AcroFields fields, Map<String, String> data) {
        try {
            for (String key : data.keySet()) {
                String value = data.get(key);
                fields.setFieldProperty(key,"textsize",15.3f,null);
                fields.setField(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 填充模板中图片
     * @param stamper
     * @param form
     * @param field
     * @param fieldValue
     */
    private void addImage(PdfStamper stamper, AcroFields form, String field, String fieldValue){
        try{
            java.util.List<AcroFields.FieldPosition> photograph = form.getFieldPositions(field);
            if(photograph!=null && photograph.size()>0){
                Rectangle rect= photograph.get(0).position;
                Image img = Image.getInstance(fieldValue);
                img.scaleToFit(rect.getWidth(), rect.getHeight());
                img.setBorder(2);
                img.setAbsolutePosition(
                        photograph.get(0).position.getLeft() + (rect.getWidth() - img.getScaledWidth() )
                        , photograph.get(0).position.getTop() - (rect.getHeight()));
                PdfContentByte cb = stamper.getOverContent((int)photograph.get(0).page);
                cb.addImage(img);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public Map<String, String> data() {
        Map<String, String> data = new HashMap<String, String>();
        data.put("id", "2");
        data.put("school", "日照保安12驾驶培训有限公司");
        data.put("phone","18006336666");
        data.put("referrer","日照保安12");
        data.put("imgPath","http://localhost/mp.jpg");
        return data;
    }

    public static void main(String[] args) throws IOException {
        AdmissionCardUtil instance = AdmissionCardUtil.getInstance();
        instance.createJpg(instance.data());
    }
}
